package com.badibadi.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import com.badibadi.activity.AfterLandingActivity;
import com.badibadi.activity.ClubApplicationFormActivity;
import com.badibadi.activity.ClubHomepageActivity;
import com.badibadi.activity.MyDataActivity;
import com.badibadi.activity.SeeOtherPeopleSpaceActivity;
import com.badibadi.infos.Club_Application_form_Model;
import com.badibadi.infos.Club_Form_Models;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.ViewHolder;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.SeeApplyFormActivity;
import com.libjph.util.JsonUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

//fragment_club_applicationform_seeform fragment_club_applicationform_seeform
//fragment_club_applicationform_seeform

public class ClubApplicationFormFragment0 extends BaseFragment implements
		IXListViewListener {

	private XListView mListView;
	private int Flags = 0, Page;
	private String type, cid, showType, c_name;
	private Results results;
	private List<Club_Form_Models> club_Form_Models, list;
	// private Club_Form_Models club_Form_Models;
	private ClubApplicationFormFragmentAdapter mAdapter;
	private int pos = 0;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_net_error));
					onLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:
				try {
					Utils.ExitPrgress(getActivity());
					club_Form_Models.addAll(list);
					mAdapter.notifyDataSetChanged();
					onLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 3:
				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_xa10));
					onLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 4:
				try {
					mListView.startLoadMore();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;

			default:
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		// mHandler = new Handler();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		type = getArguments().getString("editcontent");
		cid = getArguments().getString("cid", "0");
		showType = getArguments().getString("showType", "user");
		c_name = getArguments().getString("c_name", null);
		Page = 0;
		View view = inflater.inflate(
				R.layout.fragment_clubapplicationform_import_layout, null);
		club_Form_Models = new ArrayList<Club_Form_Models>();
		mListView = (XListView) view
				.findViewById(R.id.fragment_clubapplication_form_listView1);
		mListView.setPullLoadEnable(true);
		mAdapter = new ClubApplicationFormFragmentAdapter(getActivity(), type);
		mListView.setAdapter(mAdapter);
		mListView.setXListViewListener(this);
		mListView.startLoadMore();
		// apply("user", "1", type, Page, "0");
		return view;
	}

	private void apply(final String showType, final String uid,
			final String type, final int page, final String cid) {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				list = new ArrayList<Club_Form_Models>();
				String content = Utils.getRequest(Constants.BadiUrl_1
						+ "personal/apply?showType=" + showType + "&uid=" + uid
						+ "&type=" + type + "&page=" + page
						+ "&showNum=10&cid=" + cid);
				System.out.println("julebu"+content);
				//    ("地址是:" + Constants.BadiUrl_1
				// + "personal/apply?showType=" + showType + "&uid=" + uid
				// + "&type=" + type + "&page=" + page
				// + "&showNum=10&cid=" + cid);
//				   
//						+ "personal/apply?showType=" + showType + "&uid=" + uid
//						+ "&type=" + type + "&page=" + page
//						+ "&showNum=10&cid=" + cid);
				if (content != null) {
					results = Utils.checkResult_NNN(getActivity(), content);
					if (results != null && !results.getRetmsg().equals("null")
							&& results.isRet()) {
						try {
							//    ("申请表的返回值是:" + content);
//							   
							list = JsonUtil.getListByJsonString(
									results.getRetmsg(), Club_Form_Models.class);
							handler.sendEmptyMessage(2);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	/**
	 * 在这里面添加数据和更新适配器
	 */
	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		Page = 1;
		club_Form_Models.clear();
		apply(showType, Utils.getUid(getActivity()), type, Page, cid);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		apply(showType, Utils.getUid(getActivity()), type, ++Page, cid);
	}

	protected void onLoad() {
		// TODO Auto-generated method stub
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView
				.setRefreshTime(getResources().getString(R.string.wx_ganggang));
	}

	public class ClubApplicationFormFragmentAdapter extends BaseAdapter {
		private DisplayImageOptions options;
		private Context context;
		private Results resultssd;
		private String tempp;
		private Handler handler_1 = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					try {
						Utils.ExitPrgress(getActivity());
						Utils.showMessage(getActivity(), getResources()
								.getString(R.string.l_net_error));
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 2:
					try {
						Utils.ExitPrgress(getActivity());
						Utils.showMessage(getActivity(), resultssd.getRetmsg());
						club_Form_Models.remove(pos);
						notifyDataSetChanged();
					} catch (Exception e) {
						// TODO: handle exception
					}

					break;
				case 3:
					try {
						Utils.ExitPrgress(getActivity());
						Utils.showMessage(getActivity(), getResources()
								.getString(R.string.l_xa10));
					} catch (Exception e) {
						// TODO: handle exception
					}
					break;

				default:
					break;
				}
			}
		};

		public ClubApplicationFormFragmentAdapter(Context context, String temp) {
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.ic_stub)
					.showImageForEmptyUri(R.drawable.noimage)
					.showImageOnFail(R.drawable.noimage).cacheInMemory()
					.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5))
					.build();
			this.context = context;
			tempp = temp;
			//    ("个数:" + application_form_Models.size());
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return club_Form_Models.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return club_Form_Models.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		// fragment_club_applicationform_img
		// fragment_club_applicationform_friendname
		public View getView(final int position, View converView, ViewGroup arg2) {
			// TODO Auto-generated method stub
			if (converView == null) {
				converView = ViewHolder.buildView(context,
						R.layout.fragment_club_applicationform_import_layout,
						arg2);
			}
			ViewHolder viewHolder = (ViewHolder) converView.getTag();
			ImageView fragment_club_applicationform_img = (ImageView) viewHolder
					.getViewById(R.id.fragment_club_applicationform_img);
			ImageView fragment_club_applicationform_ok = (ImageView) viewHolder
					.getViewById(R.id.fragment_club_applicationform_ok);
			ImageView fragment_club_applicationform_no = (ImageView) viewHolder
					.getViewById(R.id.fragment_club_applicationform_no);
			TextView fragment_club_applicationform_friendname = (TextView) viewHolder
					.getViewById(R.id.fragment_club_applicationform_friendname);
			TextView fragment_club_applicationform_clubname = (TextView) viewHolder
					.getViewById(R.id.fragment_club_applicationform_clubname);
			TextView fragment_club_applicationform_seeform = (TextView) viewHolder
					.getViewById(R.id.fragment_club_applicationform_seeform);
			TextView fragment_club_applicationform_time = (TextView) viewHolder
					.getViewById(R.id.fragment_club_applicationform_time);
			// LinearLayout fragment_tongyi_or_notongyi = (LinearLayout)
			// viewHolder
			// .getViewById(R.id.fragment_tongyi_or_notongyi);
			LinearLayout fragment_yincang_anniu = viewHolder
					.getViewById(R.id.fragment_yincang_anniu);
			LinearLayout see_shenqingbiao = viewHolder
					.getViewById(R.id.see_shenqingbiao);

			// if (cid.equals("0")) {
			// fragment_yincang_anniu.setVisibility(View.GONE);
			// } else {
			// fragment_yincang_anniu.setVisibility(View.VISIBLE);
			// }

			if (tempp.equals("0")) {// 待定状态
				fragment_club_applicationform_ok
						.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View arg0) {
								// Toast.makeText(context, "同意", 0).show();
								pos = position;
								applyClub(
										club_Form_Models.get(position).getUid(),
										club_Form_Models.get(position).getCid(),
										"1");
							}
						});
				fragment_club_applicationform_no
						.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View arg0) {
								// Toast.makeText(context, "不同意", 0).show();
								pos = position;
								applyClub(
										club_Form_Models.get(position).getUid(),
										club_Form_Models.get(position).getCid(),
										"2");
							}
						});
			} else if (tempp.equals("1")) {// 同意
				fragment_club_applicationform_ok.setVisibility(View.VISIBLE);
				fragment_club_applicationform_no.setVisibility(View.GONE);
			} else if (tempp.equals("2")) {// 不同意
				fragment_club_applicationform_ok.setVisibility(View.GONE);
				fragment_club_applicationform_no.setVisibility(View.VISIBLE);
			} else {
//				   ("错误:" + tempp);
			}

			ImageLoader.getInstance().displayImage(
					Constants.BadiDownImgUrl
							+ club_Form_Models.get(position).getUser()
									.getHead() + Constants.appPhoto4img,
					fragment_club_applicationform_img, options);
			fragment_club_applicationform_friendname.setText(club_Form_Models
					.get(position).getUser().getNickName());
			fragment_club_applicationform_time.setText(Utils.Get_Data(
					club_Form_Models.get(position).getApply_time(), "MM-dd",
					"000"));
			// 俱乐部
			fragment_club_applicationform_clubname
					.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (club_Form_Models.get(position).getClub() != null) {
								if (club_Form_Models.get(position).getClub()
										.getId() != null) {
									String iid = club_Form_Models.get(position)
											.getClub().getId();
									Intent intent = new Intent(getActivity(),
											ClubHomepageActivity.class);
									intent.putExtra("cid", iid);
									startActivity(intent);
								}
							} else {
								((ClubApplicationFormActivity) getActivity())
										.finish();
							}
						}
					});

			// 名字
			fragment_club_applicationform_friendname
					.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (club_Form_Models.get(position).getUser() != null) {
								if (club_Form_Models.get(position).getUser()
										.getId() != null) {
									String iid = club_Form_Models.get(position)
											.getUser().getId();
									if (iid.equals(""
											+ Utils.getUid(getActivity()))) {
										Intent intent = new Intent(
												getActivity(),
												MyDataActivity.class);
										// intent.putExtra("friend_id",
										// iid);
										startActivity(intent);
									} else {
										Intent intent = new Intent(
												getActivity(),
												SeeOtherPeopleSpaceActivity.class);
										intent.putExtra("friend_id", iid);
										startActivity(intent);
									}
								}
							}
						}
					});

			// 头像
			fragment_club_applicationform_img
					.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (club_Form_Models.get(position).getUser() != null) {
								if (club_Form_Models.get(position).getUser()
										.getId() != null) {
									String iid = club_Form_Models.get(position)
											.getUser().getId();
									if (iid.equals(""
											+ Utils.getUid(getActivity()))) {
										Intent intent = new Intent(
												getActivity(),
												MyDataActivity.class);
										// intent.putExtra("friend_id",
										// iid);
										startActivity(intent);
									} else {
										Intent intent = new Intent(
												getActivity(),
												SeeOtherPeopleSpaceActivity.class);
										intent.putExtra("friend_id", iid);
										startActivity(intent);
									}
								}
							}
						}
					});

			try {
				if (club_Form_Models.get(position).getClub() != null) {
					if (club_Form_Models.get(position).getClub().getIs_apply() != null
							&& club_Form_Models.get(position).getClub()
									.getIs_apply().equals("0")) {
						see_shenqingbiao.setVisibility(View.GONE);
					} else if (club_Form_Models.get(position).getClub()
							.getIs_apply().equals("1")) {
						if (club_Form_Models
								.get(position)
								.getClub()
								.getC_uid()
								.equals(club_Form_Models.get(position).getUid())) {
							see_shenqingbiao.setVisibility(View.GONE);
						} else {
							see_shenqingbiao.setVisibility(View.VISIBLE);
						}
					} else {

					}
				}
			} catch (Exception e) {
				// TODO: handle exception
				see_shenqingbiao.setVisibility(View.VISIBLE);

			}

			if (c_name == null) {
				if (club_Form_Models.get(position).getClub() != null) {
					if (club_Form_Models.get(position).getClub() != null) {
						fragment_club_applicationform_clubname
								.setText(club_Form_Models.get(position)
										.getClub().getName());
					} else {
						fragment_club_applicationform_clubname.setText("");
					}

				}
			} else {
				fragment_club_applicationform_clubname.setText("" + c_name);
			}
			// 查看申请表
			fragment_club_applicationform_seeform
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							try {
								Intent intent = new Intent(context,
										SeeApplyFormActivity.class);
								if (club_Form_Models.get(position).getClub() != null) {
									intent.putExtra("cid", club_Form_Models
											.get(position).getClub().getId());
								} else {
									intent.putExtra("cid", club_Form_Models
											.get(position).getCid());
								}
								intent.putExtra("apply",
										club_Form_Models.get(position).getId());
								intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
								startActivity(intent);
							} catch (Exception e) {
								// TODO: handle exception
							}
						}
					});
			if (tempp.equals("0")) {// 待定状态
				if (club_Form_Models.get(position).getUid()
						.equals(Utils.getUid(getActivity()))) {
					fragment_yincang_anniu.setVisibility(View.GONE);
				} else {
					fragment_yincang_anniu.setVisibility(View.VISIBLE);
				}
			}

			return converView;
		}

		/**
		 * 
		 * @param apply_uid申请人id
		 * @param cid俱乐部id
		 * @param is_pass是否同意
		 */
		private void applyClub(final String apply_uid, final String cid,
				final String is_pass) {
			Utils.showPrgress(getActivity());
			MyThreadTool.fixedThreadPool.execute(new Runnable() {

				@Override
				public void run() {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("uid", Utils.getUid(getActivity()));
					map.put("apply_uid", apply_uid);
					map.put("cid", cid);
					map.put("is_pass", is_pass);
					String content = Utils.sendRequest(map, Constants.BadiUrl_1
							+ "club/applyClub");
					if (content != null) {
						resultssd = Utils.checkResult_NNN(getActivity(),
								content);
						if (resultssd != null
								&& !resultssd.getRetmsg().equals("null")
								&& resultssd.isRet()) {
							handler_1.sendEmptyMessage(2);
						} else {
							handler_1.sendEmptyMessage(3);
						}
					} else {
						handler_1.sendEmptyMessage(1);
					}
				}
			});
		}
	}

}
